package dao

import (
	"gorm.io/gorm"
	"myserver/model"
	"myserver/param"
	"myserver/tool"
)

type WorkDao struct {
	*tool.MyOrm
}

func (d *WorkDao) GetSubsidy(m *model.Work) *gorm.DB {
	res := d.Db.First(&m)
	return res
}

func (d *WorkDao) CreateWork(work model.Work) int64 {
	res := d.Db.Create(&work)
	return res.RowsAffected
}

func (d *WorkDao) DeleteWork(work model.Work) int64 {
	res := d.Db.Delete(&work)
	return res.RowsAffected
}

func (d *WorkDao) UpdateWork(work model.Work) int64 {
	res := d.Db.Updates(&work)
	return res.RowsAffected
}

func (d *WorkDao) GetWorkPage(pageParam param.PageParam) param.ResponsePageParam {
	rs := param.ResponsePageParam{}
	rs.Data = []model.Work{}
	db := d.Db.Model(&model.Work{})
	if pageParam.SearchContent != "" {
		db = db.Where("work_name LIKE ?", "%"+pageParam.SearchContent+"%")
	}
	db.Order("ID ASC").Count(&rs.Total).Limit(pageParam.Limit).Offset(pageParam.Page).Find(&rs.Data)
	return rs
}

func (d *WorkDao) GetRsWork(m *model.Work) int64 {
	db := d.Db
	var count int64
	db.Raw("SELECT count(*) FROM user_works WHERE work_id = ?", m.ID).Distinct("user_id", "work_id").Count(&count)
	return count
}

func (d *WorkDao) CreateRsWork(reservation model.Reservation) int64 {
	db := d.Db
	res := db.Exec("INSERT INTO user_works VALUES (?, ?)", reservation.UserID, reservation.ResourceID)
	return res.RowsAffected
}

func (d *WorkDao) UserWorks(pageParam param.PageParam) param.ResponsePageParam {
	rs := param.ResponsePageParam{}
	rs.Data = []model.Work{}
	db := d.Db
	db.Table("users").Select("works.work_name, works.id, works.describe, works.amount, works.money, works.work_image").Joins("left join user_works on user_works.user_id = users.id and users.id = ?", pageParam.UserId).Joins(
		"left join works on user_works.work_id = works.id and works.id is not null").Where("user_id = ?", pageParam.UserId).Order("ID desc").Count(&rs.Total).Limit(pageParam.Limit).Offset(pageParam.Page).Find(&rs.Data)
	return rs
}
